package org.aplombh.java.leetcode.all;

import java.util.Arrays;

public class _14最长公共前缀 {

}

// 排序
class Solution14_1 {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length < 1)
            return "";
        if (strs.length == 1)
            return strs[0];

        int len = strs.length;
        int i = 0;

        Arrays.sort(strs);
        String s1 = strs[0];
        String s2 = strs[len - 1];

        for (; i < s1.length() && i < s2.length(); i++) {
            if (s1.charAt(i) != s2.charAt(i))
                break;
        }
        return s1.substring(0, i);
    }
}

// 一次比较
class Solution14_2 {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length < 1)
            return "";
        if (strs.length == 1)
            return strs[0];

        String str = strs[0];

        for (int i = 1; i < strs.length; i++) {
            while (!strs[i].startsWith(str)) {
                str = str.substring(0, str.length() - 1);
                if (str.equals(""))
                    return "";
            }
        }
        return str;
    }
}
